跳到主要内容

2.6-@ 规则

Create by fall on 14 Nov 2023 Recently revised in 03 Jul 2024

@starting-style

该规则会作用在第一次接收了样式更新后。比如,当元素加载完成,出现到屏幕后

@layer

创建级联层,包含作用于该层内部的 CSS 规则。

创建级联层


@layer utilities {
.padding-sm {
padding: 0.5rem;
}

.padding-lg {
padding: 0.8rem;
}
}
/* 通过 @import 来创建 */
@import (utilities.css) layer(utilities);
/* 创建只有名称的级联层,不指定任何样式 */
@layer utilities;

优先级

@layer theme, layout, utilities;
/* 即使 tuilities 中的层级低于 theme,utilities 中的样式仍然是启用的 */
/* 后者会覆盖前者,哪怕选择器优先级并不高 */

级联层嵌套

@layer framework {
@layer layout {
}
}

// 向 layout 附加规则
@layer framework.layout{
p{
background-color:magenta;
}
}

多层样式优先级

// 通过调整位置可以调整不同层级的优先级
@layer pageBase, pagePro;

@layer pagePro {
.edit-class {
background-color: blue
}
}

@layer pageBase {
.edit-class {
background-color: magenta
}
}

@import

@keyframes

@font-face

@media

@container

container 为容器提供了监听单个容器宽度的方式,以及通过 container-name 指定对应的 @container

使用语法

@container <container-condition> {
<stylesheet>
}

使用示例

// 如果没有名称,样式将会应用到所有容器宽度上下文中
@container (width > 400 px) {
h2 {
color:magenta;
}
}
@container higher-line (height > 30rem) {
h2 {
line-height: 1.6;
}
}

除此之外,还包含了一些逻辑运算符

  • and 多个条件同时满足
  • or 满足其中一个条件
  • not 除此条件之外,每个 @container 只允许使用一次,并且不能和 andor 同时使用
@container (width > 400px) or (height > 400px) {
/* <stylesheet> */
}
@container not (width < 400px) {
/* <stylesheet> */
}

容器命名

.post {
// 用于筛选匹配的 container 名称
container-name: sidebar;
// 使用 container-type 创建 container 上下文
container-type: inline-size;
}
// 可以简写为以下方式
// container: <name> / <type>

嵌套问题

不允许在一个容器中指定多个 container,但是允许嵌套容器查询,达到相同的效果

@container summary (min-width: 400px) {
// 样式 A
@container (min-width: 800px) {
// 样式 B
/* <stylesheet> */
}
}
// 宽度在 400 - 800 时,使用样式 A,在 800 以上,使用样式 B
// 满足外层 summary 查询时,样式生效,再满足其它查询时(在此为 B)样式 B 生效
// 当然,如果不满足最外层查询,那就都不生效

实际用例

// 首先为容器命名
.panel {
container: layers-panel / inline-size;
}
.card {
padding: 1rem;
}
// 当宽度大于 20rem 时,.card padding 为 2rem
@container layers-panel (min-width: 20rem) {
.card {
padding: 2rem;
background-color:#0066aa;
}
}
<div class="panel">
<div class="card">
</div>
</div>

参考文章

作者名称